//
//  KLMMMViewController.m
//  ShowMe
//
//  Created by 123 on 2018/8/30.
//  Copyright © 2018年 nkl. All rights reserved.
//

/**
 发文流程梳理
 1.点击写文章进入界面的时候就创建文章,在后台数据库创建文章,isVisiable = false 不发布,在公告板块是不可见的,仅作者可见.
 2.点击图片上传图片,默认压缩0.7图片质量,所有图片上传完成后,路径存放在ImageSource表中.根据文章objectid设置
   一对多关系,方便删除文章的时候统一删除图片
 3.图片默认根据手机屏幕宽度伸缩
 4.点击发布 根据文章objectid 更新数据库内容即可
 */

#import "KLWriteArticleViewController.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <WordPressEditor/WPEditorField.h>
#import <WordPressEditor/WPEditorView.h>
#import <WordPressEditor/WPImageMeta.h>
#import "AnnouncesModel.h"
#import "ChoseArticleTypeView.h"
#import "ClassModel.h"
@interface KLWriteArticleViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,ChoseArticleTypeViewDelegate>

@property(nonatomic, strong) NSMutableDictionary *mediaAdded;

@property(nonatomic, strong) NSString *selectedMediaID;

@property(nonatomic, strong) NSCache *videoPressCache;

@property(nonatomic, strong) NSMutableArray *imageArray;
@property(nonatomic, strong) NSMutableArray *imageIDArray;
@property(nonatomic, strong) NSMutableArray *thumbnailArray;
@property(nonatomic, strong) NSMutableArray *typeArray;
@property(nonatomic,strong) AnnouncesModel * announces_model;
@end

@implementation KLWriteArticleViewController

#pragma mark - 懒加载
-(NSCache *)videoPressCache{
    if(!_videoPressCache){
        _videoPressCache = [[NSCache alloc] init];
    }
    return _videoPressCache;
}

-(NSMutableDictionary *)mediaAdded{
    if(!_mediaAdded){
        _mediaAdded = [NSMutableDictionary dictionary];
    }
    return _mediaAdded;
}

-(NSMutableArray *)imageArray{
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

-(NSMutableArray *)imageIDArray{
    if (!_imageIDArray) {
        _imageIDArray = [NSMutableArray array];
    }
    return _imageIDArray;
}
-(NSMutableArray *)thumbnailArray{
    if (!_thumbnailArray) {
        _thumbnailArray = [NSMutableArray array];
    }
    return _thumbnailArray;
}
-(NSMutableArray *)typeArray{
    if(!_typeArray){
        _typeArray = [NSMutableArray array];
    }
    return _typeArray;
}
-(AnnouncesModel *)announces_model{
    if(!_announces_model){
        AnnouncesModel * tempModel = [AnnouncesModel objectWithClassName:__Announces__];
        BmobUser * author = [BmobUser objectWithoutDataWithClassName:@"_User" objectId:[[UserConfig currentUser] objectId]];
        [tempModel setObject:author forKey:@"Ann_userid"];
        tempModel.Ann_sort = @1;
        tempModel.topic = @"新建文章";
        tempModel.isVisiable = @"false";
        _announces_model = tempModel;
    }
    return _announces_model;
}
#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestList];
    [self initShowView];
    [self createArticle];
}

-(void)createArticle{

    [self.announces_model sub_saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {}else{NSLog(@"文章创建失败,请检查你的网络");}
    }];
}

-(void)initShowView{
    //初始化文本
    self.titlePlaceholderText = @"文章标题";
    self.bodyPlaceholderText = @"正文";
    //相册点击事件
    __kWeakSelf__
    self.pressEventblock = ^(WPEditorViewController * vc){
        [weakSelf showPhotoPicker];
    };
}

-(void)initNavBarButton {
    
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setTitle:@"取消" forState:UIControlStateNormal];
    [leftBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(cancelPublish) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"类型" forState:UIControlStateNormal];
    [rightBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightBtn addTarget:self action:@selector(choseArticleTpye) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * rightBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn2 setTitle:@"发布" forState:UIControlStateNormal];\
    [rightBtn2 addTarget:self action:@selector(publishArticle) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn2 setTitleColor:ThemeColor forState:UIControlStateNormal];
    rightBtn2.titleLabel.font = [UIFont systemFontOfSize:14];
    
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    UIBarButtonItem * rightItem2 = [[UIBarButtonItem alloc] initWithCustomView:rightBtn2];
    self.navigationItem.rightBarButtonItems = @[rightItem2,rightItem];
    
}


#pragma mark - 请求数据
-(void)requestList{
    BmobQuery * query = [BmobQuery queryWithClassName:__TypeClass__];
    [self.typeArray removeAllObjects];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (!error) {
            [self initNavBarButton];
        }
        for (BmobObject * objc in array) {
            ClassModel * model = [[ClassModel alloc] initFromBmobObject:objc];
            [self.typeArray addObject:model];
        }
    }];
}
#pragma mark - 点击事件
-(void)choseArticleTpye{
    ChoseArticleTypeView * choseView = [[ChoseArticleTypeView alloc] initWithFrame:appWindow.bounds];
    choseView.delegate = self;
    [choseView setDataForView:self.typeArray];
    NSInteger m_index = self.announces_model.Ann_classid == nil ? -1 : [self.announces_model.Ann_classid integerValue];
    [choseView setSelectedIndex:m_index];//默认选中-1,未选中
    [appWindow addSubview:choseView];
}

-(void)pushButtonClickEvent:(NSInteger)index currentView:(ChoseArticleTypeView *)currentView{
    if(index==-1){
        [ProgressHUD showSmallErroHUD:@"当前类型未做改动"];
    }else{
        [ProgressHUD showSmallSuccessHUD:@"选择成功"];
        self.announces_model.Ann_classid = [NSNumber numberWithInteger:index];
        [currentView setSelectedIndex:(NSInteger)self.announces_model.Ann_classid];
    }
    [currentView removeFromSuperview];
}

//键盘监听事件
-(void)editorToolbarView:(WPEditorFormatbarView *)editorToolbarView showHTMLSource:(UIBarButtonItem *)barButtonItem{
    [self.view endEditing:YES];
}
//取消发布
-(void)cancelPublish{
    UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:@"警告" message:@"退出本次编辑将失去已经编写的内容" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"依然退出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [alertVc dismissViewControllerAnimated:YES completion:nil];
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            //开启线程,背地里删除网上数据
            [self confirmCancel];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        });
       
    }];
    UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertVc dismissViewControllerAnimated:YES completion:nil];
    }];
    [alertVc addAction:action1];
    [alertVc addAction:action2];
    [self presentViewController:alertVc animated:YES completion:nil];
}
//确认取消

-(void)confirmCancel{
    /**
     思路:
     0.如果没有插入图片,则什么都不需要执行,直接删除文章即可
     1.删除图片文件
     2.删除图片路径/关联
     3.删除文章
     */
    BmobQuery * query = [BmobQuery queryWithClassName:@"ImageSource"];
    [query whereObjectKey:@"thumbnailUrls" relatedTo:self.announces_model];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (array.count == 0) {
            [self.announces_model deleteInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
                if (isSuccessful) {
                    NSLog(@"删除文章成功");
                }
            }];
            return;
        }
        if(error == nil){
            BmobObjectsBatch * batch = [[BmobObjectsBatch alloc] init];
            NSMutableArray * fileUrlArray = [NSMutableArray array];
            for (int i = 0; i<array.count; i++) {
                BmobObject * obj = (BmobObject *)array[i];
                [batch deleteBmobObjectWithClassName:@"ImageSource" objectId:obj.objectId];
                [fileUrlArray addObject:[obj objectForKey:@"imageurl"]];
            }
            //删除文件
            [BmobFile filesDeleteBatchWithArray:fileUrlArray resultBlock:^(NSArray *array, BOOL isSuccessful, NSError *error) {
                if (isSuccessful) {
                    //删除记录
                    [batch batchObjectsInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                        if (isSuccessful) {
                            NSLog(@"删除所有关联图片成功");
                            [self.announces_model deleteInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
                                if (isSuccessful) {
                                    NSLog(@"删除文章成功");
                                }
                            }];
                        }else{
                            NSLog(@"删除记录失败");
                        }
                    }];
                }else{
                    NSLog(@"删除文件失败");
                }
            }];
        }else{
            NSLog(@"查询关联失败");
        }
    }];
    
}

-(void)publishArticle{
    if (self.announces_model.Ann_classid == nil) {
        [ProgressHUD showSmallErroHUD:@"请选择文章发布类型"];
        return;
    }
    //更新文章内容
    self.announces_model.Ann_sort = @1;
    self.announces_model.isVisiable = @"true";
    self.announces_model.topic = self.titleText;
    self.announces_model.Body = self.bodyText;
    
    [self.announces_model sub_updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (!error) {
            [ProgressHUD showSmallSuccessHUD:[NSString stringWithFormat:@"发布成功"]];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [ProgressHUD showSmallErroHUD:[NSString stringWithFormat:@"错误码%ld",error.code]];
        }
    }];
}

#pragma mark - 相册代理方法


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        NSURL *assetURL = info[UIImagePickerControllerReferenceURL];
        [self addAssetToContent:assetURL];
    }];
    
}


/**
 *跳转相册
 */
- (void)showPhotoPicker
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.navigationBar.translucent = NO;
    picker.modalPresentationStyle = UIModalPresentationCurrentContext;
    picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
    [self.navigationController presentViewController:picker animated:YES completion:nil];
}


#pragma mark - 本地文章用
-(void)addAssetToContent:(NSURL * )m_Url{
    PHFetchResult *assets = [PHAsset fetchAssetsWithALAssetURLs:@[m_Url] options:nil];
    
    if (assets.count < 1) {
        return;
    }
    
    PHAsset *asset = [assets firstObject];
    
    if (asset.mediaType == PHAssetMediaTypeImage) {
        [self addImageAssetToContent:asset];
    }
}
/**
 *处理图片
 */
- (void)addImageAssetToContent:(PHAsset *)asset
{
    PHImageRequestOptions *options = [PHImageRequestOptions new];
    options.synchronous = NO;
    options.networkAccessAllowed = YES;
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.version = PHImageRequestOptionsVersionCurrent;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;

    [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
        NSData * templeData = [NSData dataWithData:imageData];
        [self addImageDataToContent:templeData];
        
    }];
}
/**
 图片加入文本
 */
- (void)addImageDataToContent:(NSData *)imageData
{
    //生成文件路径
    NSString *imageID = [[NSUUID UUID] UUIDString];
    NSString *path = [NSString stringWithFormat:@"%@/%@.jpg", NSTemporaryDirectory(), imageID];
    //转化成图片
    UIImage * m_image = [UIImage imageWithData:imageData];
    //转化成缩略图(两种转换方法 前一种为转换为小图,后一种根据手机宽度转换)
//    UIImage * newImage = [PublicMethod imageCompressForSize:m_image targetSize:CGSizeMake(__KLSCREENWIDTH__, __KNewSize(200))];
     UIImage * newImage = [PublicMethod imageCompressForWidth:m_image targetWidth:__KLSCREENWIDTH__];
    //压缩图片
    NSData * m_data = UIImageJPEGRepresentation(newImage, 0.7);
    [m_data writeToFile:path atomically:YES];

    [self.imageIDArray addObject:imageID];
    //插入缩略图
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.editorView insertLocalImage:[[NSURL fileURLWithPath:path] absoluteString] uniqueId:imageID];
    });

    //上传缩略图
    NSString * userName = [[UserConfig currentUser] objectForKey:@"username"];
    NSDate * date = [NSDate date];
    BmobFile * thumbnailfile = [[BmobFile alloc] initWithFileName:[NSString stringWithFormat:@"%@%@.jpg",userName,date.timestamp] withFileData:m_data];
    [thumbnailfile saveInBackground:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            BmobObject *obj = [[BmobObject alloc] initWithClassName:@"ImageSource"];
            [obj setObject:imageID forKey:@"imageID"];
            [obj setObject:thumbnailfile.url forKey:@"imageurl"];
            //保存图片url
            [obj saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                if(isSuccessful){
                    [self.editorView replaceLocalImageWithRemoteImage:thumbnailfile.url uniqueId:imageID mediaId:nil];
                    //文章关联的图片url
                    BmobObject * thirdObjc = [BmobObject objectWithoutDataWithClassName:__Announces__ objectId:self.announces_model.objectId];
                            BmobRelation * thumbnailRelation = [[BmobRelation alloc] init];
                            [thumbnailRelation addObject:[BmobObject objectWithoutDataWithClassName:@"ImageSource" objectId:obj.objectId]];
                            [thirdObjc addRelation:thumbnailRelation forKey:@"thumbnailUrls"];
                            [thirdObjc updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                                if (isSuccessful) {
                                    NSLog(@"关联图片URL成功");
                                }else{
                                    NSLog(@"关联图片URL失败");
                                }
                            }];

                }else{
                    NSLog(@"图片上传成功,但是保存图片URL出错,请检查你的网络,错误码%ld",error.code);
                }
            }];
        }else{
            NSLog(@"图片上传失败,请检查你的网络,错误码%ld",error.code);
        }
    } withProgressBlock:^(CGFloat progress) {
        [self.editorView setProgress:progress onImage:imageID];
    }];
}


@end
